package com.black.opencvStudy;

import io.vavr.control.Try;
import org.junit.Test;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.VideoWriter;
import org.opencv.videoio.Videoio;

import java.util.concurrent.TimeUnit;

/**
 * @description：
 * @author：8568
 */
public class Demo1 extends OpencvEV {

    /**
     * 加载和显示图像
    */
    @Test
    public void readAndShowImg() {
        Mat img = Imgcodecs.imread(
                // 图片的路径
                "src/main/resources/img/img.jpg",
                // 加载的模式
                Imgcodecs.IMREAD_COLOR);
        HighGui.namedWindow("window1", HighGui.WINDOW_AUTOSIZE);
        HighGui.imshow("window1", img);
        // 一定延时后关闭窗口、设置为0的话一致阻塞到有按键输入
        int k = HighGui.waitKey(0) & 0xFF;
        HighGui.destroyWindow("window1");
        // 释放图片
        img.release();
    }

    /**
     * 读取摄像头
    */
    @Test
    public void videoCapture() {
        // index为摄像头编号、也可以传入文件路径从文件中读取
        VideoCapture videoCapture = new VideoCapture(0);
        // 帧
        Mat frame = new Mat();
        HighGui.namedWindow("window1", HighGui.WINDOW_AUTOSIZE);
        // 如果videoCapture.read(frame)读到了正确的帧、将返回true
        while (videoCapture.read(frame)) {
            HighGui.imshow("window1", frame);
            int k = HighGui.waitKey(1) & 0xFF;
        }
        HighGui.destroyWindow("window1");
        frame.release();
    }

    /**
     * 保存视频
    */
    @Test
    public void saveVideo() {
        long before = System.currentTimeMillis();
        VideoCapture videoCapture = new VideoCapture(0, Videoio.CAP_DSHOW);
        int width = (int) videoCapture.get(Videoio.CAP_PROP_FRAME_WIDTH);
        int height = (int) videoCapture.get(Videoio.CAP_PROP_FRAME_HEIGHT);
        // 帧
        Mat frame = new Mat(new Size(width, height), CvType.CV_8UC3);
        // 指定视频编码方式的4字节代码 DIVX，XVID，MJPG，X264，WMV1，WMV2 ……
        int fource = VideoWriter.fourcc('M', 'J', 'P', 'G');
        VideoWriter videoWriter = new VideoWriter(
                // 保存文件名
                "src/main/resources/img/video.avi",
                // 编码方式
                fource,
                // fps
                20,
                // 帧大小
                new Size(640, 480));
        // 读取一秒的视频
        HighGui.namedWindow("window1", HighGui.WINDOW_AUTOSIZE);
        while (videoCapture.read(frame) && System.currentTimeMillis() - before < 4000) {
            HighGui.imshow("window1", frame);
            int k = HighGui.waitKey(1) & 0xFF;
            videoWriter.write(frame);
        }
        videoWriter.release();
        videoCapture.release();
        HighGui.destroyAllWindows();
    }
}
